<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Facades\AjaxResponse;
use App\Model\User;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller{

	/**
	 * 登录验证
	 *
	 * @param Request $request
	 * @return mixed
	 */
	public function login(Request $request){
		$validator = Validator::make($request->all(), [
			'email' 	=> 'required|email',
			'password' 	=> 'required|string',
		]);
		if($validator->fails()){
			return AjaxResponse::fail(AJAX_CODE_REQUEST_PARAMS_ERROR, $validator->errors()->first());
		}
		$request['email'] = $request->input('email');
		$conditions['where'][User::FIELD_EMAIL] = $request['email'];
		$select_fields = [
			User::FIELD_USER_ID,
			User::FIELD_SALT_WORD,
			User::FIELD_PASSWORD,
		];
		$user = User::getUserByUserId($conditions, $select_fields);
		unset($conditions, $select_fields);
		if($user){
			$password = User::encryptPassword($request->input('password'), $user['salt_word']);
			if($password == $user['password']){
				$conditions['where'][User::FIELD_USER_ID] = $user['user_id'];
				$select_fields = [
					User::FIELD_USER_ID,
					User::FIELD_EMAIL,
					User::FIELD_USER_NAME,
					User::FIELD_CREATED_TIME,
					User::FIELD_UPDATED_TIME,
				];
				$user_info = User::getUserByUserId($conditions, $select_fields);
				$this->buildSession($user_info);
				return AjaxResponse::success();
			}else{
				return AjaxResponse::fail(AJAX_CODE_LOGIN_FAIL);
			}
		}else{
			return AjaxResponse::fail(AJAX_CODE_ILLEGAL_USER);
		}
	}

	/**
	 * 登出当前账号
	 */
	public function logout(){
		session()->flush();
		$this->middleware('login');
	}
}
